package com.czl.module_service.viewmodel.inventory

import android.os.Bundle
import android.widget.PopupWindow
import com.blankj.utilcode.util.GsonUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.config.AppConstants
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.ImgRspBean
import com.czl.base.data.bean.tengyun.FacilityBean
import com.czl.base.data.bean.tengyun.InventoryAssetBean
import com.czl.base.data.bean.tengyun.FileBean
import com.czl.base.data.bean.tengyun.ListBean
import com.czl.base.event.LiveBusCenter
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.route.RouteCenter
import com.czl.base.util.RxThreadHelper
import com.lxj.xpopup.core.CenterPopupView
import me.yokeyword.fragmentation.SupportFragment
import java.util.ArrayList

/**
 * @author by xubin
 * PS: Not easy to write code, please indicate.
 */
class InventoryChildViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    val uc = UiChangeEvent()

    var currentPage = 1
    var execId: String? = null
    var taskId: Long? = null
    var titleName : String? = null
    // 当前操作的tab
    var tabIndex : Int? = null
    // 当前操作的标记(0-正常，1-盘盈，2-盘亏，3-删除, 4-代盘)
    var markPosition : Int = -1
    var imgList : MutableList<FileBean> = arrayListOf()
    var lastScanCode : String? = null
    // 当前操作的对象
    var scanData: InventoryAssetBean = InventoryAssetBean()

    inner class UiChangeEvent {
        val loadFinallyEvent: SingleLiveEvent<Unit?> = SingleLiveEvent()
        val loadCompleteEvent: SingleLiveEvent<ListBean<InventoryAssetBean>?> = SingleLiveEvent()
        val loadArtificialShowPopEvent: SingleLiveEvent<InventoryAssetBean?> = SingleLiveEvent()
        val loadErrorEvent: SingleLiveEvent<Unit?> = SingleLiveEvent()
        val loadSuccessEvent: SingleLiveEvent<Any> = SingleLiveEvent()
    }

    val onLoadMoreListener: BindingCommand<Void> = BindingCommand(BindingAction {
        wechatGetTaskFacilityInfoByTaskId(status = tabIndex)
    })
    val onRefreshListener: BindingCommand<Void> = BindingCommand(BindingAction {
        currentPage = 1
        wechatGetTaskFacilityInfoByTaskId(status = tabIndex)
    })

    val onScanCodeCommand: BindingCommand<Any> = BindingCommand(BindingAction {
        // 扫码
        startActivity(AppConstants.Router.Service.F_SERVICE_SCAN)
    })

    val onAssetRegisterCommand: BindingCommand<Any> = BindingCommand(BindingAction {
        // 盘盈登记
        startContainerActivity(AppConstants.Router.Service.F_SERVICE_ASSET_REGISTER, Bundle().apply {
            putSerializable("taskId", taskId)
            putSerializable("execId", execId)
        })
    })

    val onFullCheckCommand: BindingCommand<Any> = BindingCommand(BindingAction {
        // 完成
        summaryTask(taskId = taskId)
    })

    // 查询盘点设施
    fun wechatGetTaskFacilityInfoByTaskId(status: Int?) {
        model.mTengYunHttpDataSource
            .wechatGetTaskFacilityInfoByTaskId(
                GsonUtils.toJson(
                    mapOf(
                        "execId" to execId,
                        "status" to status,
                        "taskId" to taskId,
                        "facilityName" to titleName,
                        "pageNo" to currentPage,
                        "pageSize" to 100,
                    )
                )
            )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doFinally {
                uc.loadFinallyEvent.postValue(null)
            }
            .subscribe(object : ApiSubscriberHelper<BaseBean<ListBean<InventoryAssetBean>>>() {
                override fun onResult(t: BaseBean<ListBean<InventoryAssetBean>>) {
                    if (t.state == 0) {
                        currentPage++
                        uc.loadCompleteEvent.postValue(t.data)
                    } else {
                        uc.loadErrorEvent.postValue(null)
                    }
                }

                override fun onFailed(msg: String?) {
                    uc.loadErrorEvent.postValue(null)
                    showErrorToast(msg)
                }
            })
    }

    fun getFacilityByNo(
        facilityNo: String?
    ) {

        model.mTengYunHttpDataSource.getFacilityByNo(
            GsonUtils.toJson(
                mapOf(
                    "facilityNo" to facilityNo
                )
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<FacilityBean>>() {
                override fun onResult(t: BaseBean<FacilityBean>) {
                    if (t.state == 0) {
                        wechatSelectFacilityInfo(t.data?.id)
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

    fun wechatSelectFacilityInfo(
        facilityId: Long?
    ) {
        model.mTengYunHttpDataSource.wechatSelectFacilityInfo(
            GsonUtils.toJson(
                mapOf(
                    "facilityId" to facilityId,
                    "execId" to execId,
                    "taskId" to taskId,
                )
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<InventoryAssetBean>>() {
                override fun onResult(t: BaseBean<InventoryAssetBean>) {
                    if (t.state == 0) {
                        val dataBean = t.data
                        scanData = t.data!!
                        if (dataBean?.taskId != null && dataBean.taskId!!.compareTo(0) > 0) {
                            if (dataBean.taskId!!.compareTo(taskId!!) == 0) {
//                                /* 如果在同一个任务下，盘正常 */
                                markPosition = 0
                                substitute(
                                    isReplace = 0,    // 是否代盘 0 否   1 是
                                    inventoryId = dataBean.inventoryId,
                                    inventoryMethod = 1,  // 盘点方式 0 拍照   1扫码   2 人工盘
                                    imgList = dataBean.imgList,
                                    status = 1,
                                    // mark= type === 2 ? this.explaination : '',
                                    mark = "",
                                    planInventoryMethod = 1,
                                    pop = null,
                                    taskId = taskId,   // 任务id
                                    planInventoryMethodList = dataBean.planInventoryMethodList
                                )
                            } else {
                                uc.loadArtificialShowPopEvent.postValue(dataBean)
                            }
                        } else {
                            showNormalToast("该资产不在盘点任务中!")
                        }
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })

    }

    // 新增盘点
    fun substitute(
        isReplace: Int?,    // 是否代盘 0 否   1 是
        inventoryId: String?,
        inventoryMethod: Int?,  // 盘点方式 0 拍照   1扫码   2 人工盘
        imgList: MutableList<FileBean>?,
        status: Int?,
        // mark: type === 2 ? this.explaination : '',
        mark: String?,
        planInventoryMethod: Int?,
        taskId: Long?,   // 任务id
        planInventoryMethodList: MutableList<Int>?,
        pop: CenterPopupView?,
        tname: String? = model.getLocalUserInfo()?.nickName,
        userId: String? = model.getLocalUserInfo()?.userId,
    ) {
        model.mTengYunHttpDataSource.summaryInventoryFacility(
            GsonUtils.toJson(
                mapOf(
                    "isReplace" to isReplace,    // 是否代盘 0 否   1 是
                    "inventoryId" to inventoryId,
                    "inventoryMethod" to inventoryMethod,  // 盘点方式 0 拍照   1扫码   2 人工盘
                    "imgList" to imgList,
                    "status" to status,
                    // mark: type === 2 ? this.explaination : '',
                    "mark" to mark,
                    "planInventoryMethod" to planInventoryMethod,
                    "taskId" to taskId,   // 任务id
                    "planInventoryMethodList" to planInventoryMethodList,
                    "tname" to tname,
                    "userId" to userId
                )
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.state == 0) {
                        showNormalToast("提交成功")
                        // 返回盘点页面
                        pop?.dismiss()
                        if (inventoryMethod == 1) {
                            uc.loadSuccessEvent.postValue(100)
                        } else {
                            uc.loadSuccessEvent.postValue(1)
                        }
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    // 添加盘点说明 addInventoryNote
    fun addInventoryNote(
        isReplace: Int?,    // 是否代盘 0 否   1 是
        inventoryId: String?,
        inventoryMethod: Int?,  // 盘点方式 0 拍照   1扫码   2 人工盘
        imgList: MutableList<FileBean>?,
        status: Int?,
        // mark: type === 2 ? this.explaination : '',
        mark: String?,
        planInventoryMethod: Int?,
        taskId: Long?,   // 任务id
        planInventoryMethodList: MutableList<Int>?,
        pop: CenterPopupView?,
        tname: String? = model.getLocalUserInfo()?.nickName,
        userId: String? = model.getLocalUserInfo()?.userId,
    ) {
        model.mTengYunHttpDataSource.addInventoryNote(
            GsonUtils.toJson(
                mapOf(
                    "isReplace" to isReplace,    // 是否代盘 0 否   1 是
                    "inventoryId" to inventoryId,
                    "inventoryMethod" to inventoryMethod,  // 盘点方式 0 拍照   1扫码   2 人工盘
                    "imgList" to imgList,
                    "status" to status,
                    // mark: type === 2 ? this.explaination : '',
                    "mark" to mark,
                    "planInventoryMethod" to planInventoryMethod,
                    "taskId" to taskId,   // 任务id
                    "planInventoryMethodList" to planInventoryMethodList,
                    "tname" to tname,
                    "userId" to userId
                )
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.state == 0) {
                        showNormalToast("提交成功")
                        // 返回盘点页面
                        pop?.dismiss()
                        uc.loadSuccessEvent.postValue(1)
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    // 删除盘盈资产
    fun deleteByInventoryId(
        inventoryId : String? = null,
        pop: PopupWindow? = null
    ) {
        model.mTengYunHttpDataSource.deleteInventoryProfidByInventoryId(
            GsonUtils.toJson(
                mapOf(
                    "inventoryId" to inventoryId
                )
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.state == 0) {
                        showNormalToast("删除成功")
                        // 返回盘点页面
                        pop?.dismiss()
                        uc.loadSuccessEvent.postValue(1)
                        if (pop != null)
                            pop.dismiss()
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    // 完成
    private fun summaryTask(
        taskId: Long?
    ) {
        model.mTengYunHttpDataSource.summaryTask(
            GsonUtils.toJson(
                mapOf(
                    "taskId" to taskId
                )
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.state == 0) {
                        showNormalToast("提交成功")
                        // 返回盘点页面
                        uc.loadSuccessEvent.postValue(1000)
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    // 拍照盘点
    fun uploadHeadImg(imgSrc: String) {
        model.apply {
            uploadHeadImg("szchd", imgSrc, "assets")
                .compose(RxThreadHelper.rxSchedulerHelper(this@InventoryChildViewModel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriberHelper<BaseBean<ImgRspBean>>() {
                    override fun onResult(t: BaseBean<ImgRspBean>) {
                        dismissLoading()
                        if (t.data == null) return
                        if (t.code == 200) {
                            val bean: ImgRspBean = t.data!!
                            val fileBean = FileBean()
                            fileBean.imgOrder = 1
                            fileBean.imgUrl = bean.url
                            imgList.add(fileBean)
                            LiveBusCenter.postUploadImgReturnEvent(1)
                        } else {
                            showErrorToast(t.msg)
                        }
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showErrorToast(msg)
                    }

                })
        }
    }
}